﻿using ManageReportVer1.Models;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace ManageReportVer1.Controllers
{
    [Authorize(Roles = "User,Admin")]
    public class ItemController : Controller
    {
        //  private object childItems;
        //
        // GET: /Item/

        public ActionResult AddItem()
        {
            // ItemModel item = new ItemModel();
            DBDataContext context = new DBDataContext();
            IEnumerable<Item> Items = (IEnumerable<Item>)context.Items;
            List<DropDownListModel> thuVienItems = new List<DropDownListModel>();
            for (int i = 0; i < Items.Count()+1; i++)
            {
                if (i == 0)
                {
                    thuVienItems.Add(new DropDownListModel { Value = "0", Name = "Chọn Đầu mục cha" });
                }
                else
                {
                    thuVienItems.Add(new DropDownListModel { Value = Items.ElementAt(i-1).ItemId.ToString(), Name = Items.ElementAt(i-1).ItemName.ToString() });
                }
                }
            ItemModel model = new ItemModel();
            model.ItemList = new SelectList(thuVienItems, "Value", "Name");
            return View(model);
        }
        [HttpPost]
        public ActionResult AddItem(ItemModel item)
        {
            DBDataContext context = new DBDataContext();
            if (ModelState.IsValid)
            {
                Item items = new Item();
                items.ItemName = item.ItemName;
                items.DepartmentId = item.DepartmentId;
                items.ParentsId = item.itemID;

                context.Items.InsertOnSubmit(items);
                context.SubmitChanges();
                return RedirectToAction("ViewItem", "Item");
            }
            IEnumerable<Item> Items = (IEnumerable<Item>)context.Items;
            List<DropDownListModel> thuVienItems = new List<DropDownListModel>();
            for (int i = 0; i < Items.Count() + 1; i++)
            {
                if (i == 0)
                {
                    thuVienItems.Add(new DropDownListModel { Value = "0", Name = "Chọn Đầu mục cha" });
                }
                else
                {
                    thuVienItems.Add(new DropDownListModel { Value = Items.ElementAt(i - 1).ItemId.ToString(), Name = Items.ElementAt(i - 1).ItemName.ToString() });
                }
            }

            item.ItemList = new SelectList(thuVienItems, "Value", "Name");
            return View(item);
        }


        //View Item
        public ActionResult ViewItem()
        {
            DBDataContext context = new DBDataContext();
            int roleID = ManageReportVer1.Utils.GetRoleOFUser(User.Identity.Name);
            int departmentID = ManageReportVer1.Utils.GetDepartmentIdOFUser(User.Identity.Name);
            if (roleID == 1)
            {
                var item = from s in context.Items where s.DepartmentId == departmentID orderby s.ItemId ascending select s;
                return View(item.ToList());
            }
            if (roleID == 2)
            {
                var item = from s in context.Items orderby s.ItemId ascending select s;
                return View(item.ToList());
            }
            return View();
        }
        //update Item
        [HttpGet]
        public ActionResult UpdateItem(string id)
        {
            int itemId = Convert.ToInt32(id);
            DBDataContext context = new DBDataContext();
            Item item= context.Items.Single(n => n.ItemId == itemId);
            return View(item);
        }

        [HttpPost]
        public ActionResult UpdateItem(Item item)
        {
            DBDataContext context = new DBDataContext();
            if (ModelState.IsValid)
            {
                Item itemUpdate = context.Items.Single(s => s.ItemId == item.ItemId);
                itemUpdate.ItemName = item.ItemName;
                itemUpdate.DepartmentId = item.DepartmentId;
                itemUpdate.ParentsId = item.ParentsId;

                context.SubmitChanges();
                return RedirectToAction("ViewItem", "Item");
            }
            return View(item);
        }

        //Delete Item
        public ActionResult DeleteItem(string id)
        {
            int itemId = Convert.ToInt32(id);
            DBDataContext context = new DBDataContext();
            Item item = context.Items.Single(n => n.ItemId == itemId);
            context.Items.DeleteOnSubmit(item);
            context.SubmitChanges();
            return RedirectToAction("ViewItem", "Item");
        }

        //View Detail Item
        private StringBuilder sbMenu = new StringBuilder();
        public ActionResult ViewDetailItem()
        {
            DBDataContext db = new DBDataContext();
            int departmentID = ManageReportVer1.Utils.GetDepartmentIdOFUser(User.Identity.Name);
            sbMenu.Append("<ul class=abcd>");
            var lstTop = from p in db.Items
                         where p.ParentsId == 0 & p.DepartmentId==departmentID
                         select p;

            foreach (var objPage in lstTop)
            {
                sbMenu.AppendFormat("<li class=thang1><p class=thang2>{0}</p>", objPage.ItemName);
                BuildMenu(objPage.ItemId, 2);
            }

            sbMenu.Append("</ul>");
            ViewBag.Message = new MvcHtmlString(sbMenu.ToString());

            return View();
        }

        int snd,sd;
        public void BuildMenu(Int32 parentId, int check)
        {
            DBDataContext db = new DBDataContext();
            var lstChild = from p in db.Items
                           where p.ParentsId == parentId
                           select p;

            if (lstChild.Count() > 0)
            {
                sbMenu.Append("<ul class=thang>");
                foreach (var objPage in lstChild)
                {
                    sbMenu.AppendFormat("<li class=thang1><p class=thang2>{0}</p>", objPage.ItemName);
                    BuildMenu(objPage.ItemId, check);
                }
                sbMenu.Append("</ul>");
            }
            else
            {
                    var lstChild1 = from p in db.Items
                                    where p.ItemId == parentId
                                    select p;
                   // int i = 0;
                    foreach (var objPage in lstChild1)
                    {
                        int HighTree = highTree();
                        //tim do dai nguoc
                        snd = 0;
                        CountNguoc(objPage.ParentsId.Value, ref snd);

                        sbMenu.Append("<ul class=thang>");

                        if (snd < HighTree)
                        {

                            for (int ia = 0; ia < HighTree - snd; ia++)
                            {

                                sbMenu.AppendFormat("<li class=thang1><p class=thang5>&nbsp</p></li>");
                                sbMenu.Append("</br>");

                            }
                        }
                      //  sbMenu.Append("<input id=" + objPage.ItemId + "test" + i + " type=" + objPage.ItemName + " name=" + objPage.ItemName + " class=thang1212>");
                       // i++;
                        sbMenu.Append("</ul>");
                    }
                sbMenu.Append("</li>");
            }
        }
        //tim chieu dai cay
        public int highTree()
        {
            DBDataContext db = new DBDataContext();
            int high = 0;
            var lstTop1 = from p in db.Items
                          where p.ParentsId == 0
                          select p;

            foreach (var objPage in lstTop1)
            {
                sd = 0;
                Count(objPage.ItemId, ref sd);
                if (sd > high)
                {
                    high = sd;
                }
            }
            return high;
        }

        public void CountNguoc(Int32 ParentsId, ref int count1)
        {
            DBDataContext db = new DBDataContext();
            var lstChild = from p in db.Items
                           where p.ItemId == ParentsId
                           select p;
            if (lstChild.Count() > 0)
            {
                count1++;
                foreach (var th in lstChild)
                {
                    CountNguoc(th.ParentsId.Value, ref count1);
                }
            }
        }
        public void Count(Int32 ItemId, ref int count)
        {
            DBDataContext db = new DBDataContext();
            var lstChild = from p in db.Items
                           where p.ParentsId == ItemId
                           select p;
            if (lstChild.Count() > 0)
            {
                count++;
                foreach (var objPage in lstChild)
                {
                    Count(objPage.ItemId, ref count);
                }
            }
            // return count;
        }
    }
}
